<?php

namespace app\common\model;

use app\admin\model\system\SystemUserPost;
use app\admin\model\system\SystemUserRole;
use app\common\basic\BaseModel;

/**
 * 用户信息模型
 */
class SystemUser extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';
    protected $table = 'vk_ap_system_user';

    /**
     * 获取器
     */
    public function getBackendSettingAttr($value)
    {
        return json_decode($value ?? '', true);
    }

    /**
     * 根据账号/昵称搜索
     */
    public function searchUsernameAttr($query, $value) {
        if (!empty($value)) {
            $query->whereLike('username|nickname', '%'.$value.'%');
        }
    }

    public function searchNicknameAttr($query, $value) {
        if (!empty($value)) {
            $query->whereLike('nickname', '%'.$value.'%');
        }
    }

    public function searchPhoneAttr($query, $value) {
        if (!empty($value)) {
            $query->whereLike('phone|email', '%'.$value.'%');
        }
    }
    public function searchEmailAttr($query, $value) {
        if (!empty($value)) {
            $query->whereLike('email', '%'.$value.'%');
        }
    }
    
    /**
     * 根据岗位id进行搜索
     */
    public function searchPostIdAttr($query, $value)
    {
        $query->join(SystemUserPost::getTable().' post', 'user.id = post.user_id')->where('post.post_id', $value);
    }

    /**
     * 根据角色id进行搜索
     */
    public function searchRoleIdAttr($query, $value)
    {
        $query->whereIn('id', function ($query) use ($value) {
            $query->table(SystemUserRole::getTable())->where('role_id', $value)->field('user_id');
        });
    }

}